import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart';
import '../../utils/local_storage_utils.dart';

class VideoController extends GetxController {
  var videos = <AssetEntity>[].obs;
  var selectedVideoIds = <String>{}.obs;
  var searchQuery = ''.obs;

  @override
  void onInit() {
    super.onInit();
    loadVideos();
  }

  Future<void> loadVideos() async {
    List<AssetPathEntity> folders = await PhotoManager.getAssetPathList(type: RequestType.video);
    List<AssetEntity> allVideos = [];

    for (var folder in folders) {
      List<AssetEntity> videoList = await folder.getAssetListPaged(page: 0, size: await folder.assetCountAsync);
      allVideos.addAll(videoList);
    }

    videos.assignAll(allVideos);
  }

  Future<void> searchVideos(String query) async {
    searchQuery.value = query;
    List<AssetEntity> allVideos = await loadAllVideos();
    videos.assignAll(allVideos.where((video) async {
      String? title = await video.titleAsync;
      return title != null && title.toLowerCase().contains(query.toLowerCase());
    } as bool Function(AssetEntity element)).toList());
  }

  Future<List<AssetEntity>> loadAllVideos() async {
    List<AssetPathEntity> folders = await PhotoManager.getAssetPathList(type: RequestType.video);
    List<AssetEntity> allVideos = [];

    for (var folder in folders) {
      List<AssetEntity> videoList = await folder.getAssetListPaged(page: 0, size: await folder.assetCountAsync);
      allVideos.addAll(videoList);
    }

    return allVideos;
  }

  void toggleSelection(String videoId) {
    if (selectedVideoIds.contains(videoId)) {
      selectedVideoIds.remove(videoId);
    } else {
      selectedVideoIds.add(videoId);
    }
  }

  bool isSelected(String videoId) {
    return selectedVideoIds.contains(videoId);
  }
}
